package com.chang.reflect;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestCar {
    @Test
    public void test() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Car car = new Car();

        Class<Car> carClass = Car.class;

        Class<? extends Car> aClass = new Car().getClass();

        Class<?> car1 = Class.forName("com.chang.reflect.Car");

        Car car2 = (Car) car1.getConstructor().newInstance();

    }

    @Test
    public void test01() throws NoSuchMethodException {
        Class<Car> carClass = Car.class;
        Constructor[] constructors = carClass.getDeclaredConstructors(); // 获取私有和公开的全部方法 getConstructor()无法获取私有方法
        for (Constructor c : constructors
        ) {
            System.out.println("方法名称：" + c.getName());
            System.out.println("参数个数：" + c.getParameterCount());
        }
    }

    @Test
    public void test02() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<Car> clazz = Car.class;
        /*Constructor<Car> constructor = clazz.getConstructor(String.class, int.class, String.class); // 反射获取非私有化构造创建对象
        Car car = constructor.newInstance("夏利", 10, "红");*/
        Constructor<Car> constructor = clazz.getDeclaredConstructor(String.class, int.class, String.class); //反射获取私有化构造创建对象
        constructor.setAccessible(true); // 设置允许访问私有对象
        Car car = constructor.newInstance("夏利", 10, "红");
        System.out.println(car);
    }

    @Test
    public void test03() throws IllegalAccessException, InvocationTargetException {

        Car car = new Car();
        Class<Car> clazz = Car.class;
        Field[] declaredField = clazz.getDeclaredFields();

        for (Field field : declaredField
        ) {
            if (field.getName().equals("name")) {
                //设置允许访问
                field.setAccessible(true);
                field.set(car, "五菱宏光");
                System.out.println(car);
                System.out.println(field.getName());
            }
        }
        // 调用公开方法
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods
        ) {
            if (method.getName().equals("toString")) {
                String invoke = (String) method.invoke(car);
                System.out.println("toString执行了:>>>>" + invoke);
            }
        }

        // 调用私有方法

        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods
        ) {
            if (method.getName().equals("run")) {
                method.setAccessible(true);
                String invoke = (String) method.invoke(car);
                System.out.println("run:>>>>" + invoke);
            }
        }
    }
}
